package uni.call.app;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.sip.SipAudioCall;
import android.net.sip.SipException;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.ToggleButton;

public class OutGoingCall extends Activity
{	
	public static SipAudioCall OutgoingCall;
	
	public static String PeerProfile;
	public static String PeerProfileName;
	
	//Timers
	public static Timer MyTimer;
	public static Long MyTime;
	public static StopWatch MyStopWatch = new StopWatch();
	
	public static String StartTimeDate;
    
	public void onCreate(Bundle savedInstanceState)
	{	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.incall);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        String domain = prefs.getString("domainPref", "");
        PeerProfile = DailerActivity.Peer + "@"+domain;
		
        ImageButton EndBT = (ImageButton)findViewById(R.id.End);
        ToggleButton HoldBT = (ToggleButton)findViewById(R.id.Hold);
        ToggleButton SpeakerBT = (ToggleButton)findViewById(R.id.Speaker);
        ToggleButton MuteBT = (ToggleButton)findViewById(R.id.Mute);
        
        EndBT.setOnClickListener(EndListener);
        HoldBT.setOnClickListener(HoldListener);
        SpeakerBT.setOnClickListener(SpeakerListener);
        MuteBT.setOnClickListener(MuteListener);

        final String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
        StartTimeDate = sdf.format(cal.getTime());
        
        InitiateCall();

        TextView UserName = (TextView)findViewById(R.id.CallerName);
        TextView UserNumber = (TextView)findViewById(R.id.CallerNumber);
        UserName.setText(PeerProfileName);
        UserNumber.setText(DailerActivity.Peer);
	}
	    
	private void TimerMethod()
	{
		this.runOnUiThread(Timer_Tick);
	}

	private Runnable Timer_Tick = new Runnable() {
		public void run() {

			UpdateTimer(MyStopWatch.GetElapsedTime());
		}
	};

	public void UpdateTimer(final Long Status)
    {
        this.runOnUiThread(new Runnable()
        {
            public void run()
            {
                TextView TimerTV = (TextView) findViewById(R.id.CallTimer);
                TimerTV.setText(Status.toString());
            }             
        });
    }
  
    public  void InitiateCall()
    {
		//Log.v("MyActivity", "index=" +Integer.toString( call.getState())); 
        try 
        {
            SipAudioCall.Listener listener = new SipAudioCall.Listener()
            {
            	@Override
                public void onCallEstablished(SipAudioCall call)
                {
            		OutgoingCall.startAudio();
                    MyStopWatch.Start();
                    MyTimer = new Timer();
            		MyTimer.schedule(new TimerTask()
            		{
            			@Override
            			public void run()
            			{
            				TimerMethod();
            			}

            		}, 0, 1000);
                }
            	
                @Override
                public void onCallEnded(SipAudioCall call)
                {
                	if(OutgoingCall.getState() == 7)
                	{
                		Log.v("MyActivity", "index=" +"canceled");
                	}
                	else
                	{Log.v("MyActivity", "index=" +OutgoingCall.getState());
                		
                	}
                	try 
                	{
						OutgoingCall.endCall();
					} 
                	catch (SipException e1) 
                	{
						e1.printStackTrace();
					}
                     	
                	Intent myIntentt = new Intent(getApplicationContext(), HomeActivity.class);
                	startActivity(myIntentt);
                }
            };
            
            OutgoingCall = HomeActivity.SipManager.makeAudioCall(HomeActivity.MySipProfile.getUriString(), PeerProfile, listener, 30);    
			OutgoingCall.setListener(listener);
        }
        catch (Exception e)
        {
            if (HomeActivity.MySipProfile != null)
            {
                try 
                {
                    HomeActivity.SipManager.close(HomeActivity.MySipProfile.getUriString());
                } 
                catch (Exception ee)
                {
                }
            }
            if (OutgoingCall != null)
            {
            	OutgoingCall.close();
            }
        }
    }
    
    private OnClickListener EndListener = new OnClickListener() 
    {
        public void onClick(View v)
        {
        	try 
        	{
        		try
        		{
        			MyTimer.cancel();
        			MyStopWatch.Stop();
        		}
        		catch (Exception e)
        		{
        			MyStopWatch = new StopWatch();
        			MyStopWatch.StartTime= 0;
        			MyStopWatch.StopTime= 0;
				}
        		
        		MyTime =  MyStopWatch.GetElapsedTime();
        		UpdateTimer(MyTime);

        		String Duration;
        		if(MyTime/60 < 1 )
        		{
        			Duration = Long.toString(MyTime) + " Sec";
        		}
        		else
        		{
        			Duration = Long.toString(MyTime) + " Min";
        		}
        		Insert("Outgoing", PeerProfileName, DailerActivity.Peer, Duration, StartTimeDate);

        		OutgoingCall.endCall();
        		OutgoingCall.close();
        		DailerActivity.Peer = "";
	        	Intent myIntentt = new Intent(getApplicationContext(), HomeActivity.class);
	            startActivity(myIntentt);
			} 
        	catch (SipException e)
			{
				e.printStackTrace();
			}
        }
    };
    
    private OnClickListener HoldListener = new OnClickListener() 
    {
        public void onClick(View v)
        {
        	ToggleButton HoldBT = (ToggleButton)findViewById(R.id.Hold);
        	if(HoldBT.isChecked())
        	{
	        	try
	        	{
	        		OutgoingCall.holdCall(0);	
				} 
	        	
	        	catch (SipException e)
				{
				}
        	}	
        	else
        	{
        		try 
        		{
        			OutgoingCall.continueCall(0);
				} 
        		catch (SipException e) 
				{
					e.printStackTrace();
				}
        	}
        }
    };
    
    
    private OnClickListener SpeakerListener = new OnClickListener()
    {
        public void onClick(View v)
        {
        	ToggleButton SpeakerBT = (ToggleButton)findViewById(R.id.Speaker);
        	if(SpeakerBT.isChecked())
        	{
        		OutgoingCall.setSpeakerMode(true);
        	}
        	else
        	{
        		OutgoingCall.setSpeakerMode(false);
        	}
        }
    };
    
    private OnClickListener MuteListener = new OnClickListener()
    {
        public void onClick(View v)
        {
        	ToggleButton MuteBT = (ToggleButton)findViewById(R.id.Mute);
        	if(MuteBT.isChecked())
        	{
        		OutgoingCall.toggleMute();
        	}
        	else
        	{
        		OutgoingCall.toggleMute();
        	}
        }
    };
   
    public void Insert(String Type,String Name, String Number, String Duration, String Time)
    {	
    	LogDBAdapter myAdapter = new LogDBAdapter(getApplicationContext());
		myAdapter.OpenToWrite();        
		myAdapter.Insert(Type,Name,Number, Duration, Time);
		myAdapter.Close();
    }
}
